<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>WebSocket客户端</title>
</head>
<body>
    <input id="sendTxt" type="text">
    <button id="sendBtn">发送</button>
    <div id="recv"></div>
</body>

<script src="http://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    var wsServer = 'ws://127.0.0.1:9502';
    var websocket = new WebSocket(wsServer);

    websocket.onopen = function (evt) {
        console.log("Connected to WebSocket server.");
        log("Connected to WebSocket server.");
    };

    websocket.onclose = function (evt) {
        console.log("Disconnected to WebSocket server.");
    };

    websocket.onmessage = function (evt) {
        console.log('Retrieved data from server: ' + evt.data);
        log(evt.data);
        //document.getElementById("recv").innerHTML = 'Retrieved data from server: ' + evt.data;
    };

    websocket.onerror = function (evt, e) {
        console.log('Error occured: ' + evt.data);
        log('Error occured: ' + evt.data);
    };

    document.getElementById("sendBtn").onclick = function() {
        var txt = document.getElementById("sendTxt").value;
        websocket.send(txt);
    }

    //在消息框中打印内容
    function log(text) {
        $("#recv").append(text + "");
    }
</script>
</html>